export const initstate = {
  tableLists: [
    { id: 1, name: "vrgerg", age: 18, address: "6686" }, //0
    { id: 2, name: "ege", age: 19, address: "689398" }, //1
    { id: 3, name: "fwef", age: 20, address: "383838" }, //2
  ],
  isModalVisible: false,
};

export const actions = {
  deleteAction(payload) {
    return {
      type: "DELETEACTION",
      payload,
    };
  },

  upAction(payload) {
    return {
      type: "UPACTION",
      payload,
    };
  },
  downAction(payload) {
    return {
      type: "DOWNACTION",
      payload,
    };
  },
  addAction(payload) {
    return {
      type: "ADDACTION",
      payload,
    };
  },
  upDateAction(payload) {
    return {
      type: "UPDATEACTION",
      payload,
    };
  },
};

export function reducers(state = initstate, { type, payload }) {
  const newState = JSON.parse(JSON.stringify(state));
  switch (type) {
    case "DELETEACTION":
      newState.tableLists.splice(payload, 1);
      break;

    case "UPACTION":
      newState.tableLists.splice(payload - 1, 0, newState.tableLists[payload]);
      newState.tableLists.splice(payload + 1, 1);
      break;

    case "DOWNACTION":
      newState.tableLists.splice(payload + 2, 0, newState.tableLists[payload]);
      newState.tableLists.splice(payload, 1);
      break;

    case "ADDACTION":
      if (payload?.upadd) {
        newState.tableLists.push(payload);
      }

      newState.isModalVisible = !newState.isModalVisible;
      break;

    case "UPDATEACTION":
      if (payload?.updata) {
        const { id, name, age, address } = payload;
        newState.tableLists.splice(payload.index, 1, {
          id,
          name,
          age,
          address,
        });
        newState.isModalVisible = !newState.isModalVisible;
      }

      break;

    default:
      return newState;
      break;
  }
  return newState;
}
